<?php
//聚富通H5聚合支付接口V3 1.2.5：https://open.icbc.com.cn/icbc/apip/api_detail.html?apiId=10000000000000034506&baseUrl=%2Fjft%2Fui&resUrl=%2Fpay%2Fh5&version=V3&apiName=%E8%81%9A%E5%AF%8C%E9%80%9AH5%E6%94%AF%E4%BB%98%E6%8E%A5%E5%8F%A3V3&serviceId=00481&resourceId=10000000000000009441
namespace jy_icbcpay;
defined('BY_JYA') or exit('error');
class pay extends \plugin{
    public function __construct($setting=array()){
        parent::__construct('jy_icbcpay');
        $setting=uni_setting('pay');
        if(!$setting['icbcpay_appid']){
            exi('商户APP编号必须填写','error');
        }
        if($_SESSION['auth_wxid']){
            $auth_appid=pdo_getcolumn('core_account_wechat',array('id'=>$_SESSION['auth_wxid']),'appid');
        }
        $wechat_appid=$auth_appid?:$setting['wechat_appid'];
        if(!$wechat_appid){
            $wechat_appid=pdo_getcolumn('core_account_wechat',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1),'appid');
            if(!$wechat_appid){
                $wechat_appid=pdo_getcolumn('core_account_wechat',array('uniacid'=>$_SESSION['uniacid']),'appid');
            }
        }
        $this->config=array(
            'sub_appid'=>$wechat_appid,
            'app_id'=>$setting['icbcpay_appid'],
			'outVendorId'=>$setting['icbcpay_merchid'],
			'publickey'=>$setting['icbcpay_public'],
        );
    }
    //创建订单
    public function create($pay_log,$paytype='',$wxappid=''){
        # 支付设置
        if($paytype=='wechat'){
            if($_SESSION['container']=='wechat'){
                $pay_type='03';
                if(!$this->config['sub_appid']) {
                    exi('未绑定微信公众号，不能使用微信支付！', 'error');
                }
            }elseif($_SESSION['container']=='wxapp'){
                $this->config['sub_appid']=$wxappid?:$this->config['sub_appid'];
                $pay_type='13';
            }else{
				$pay_type='03';
				if(!$this->config['sub_appid']) {
                    exi('未绑定微信公众号，不能使用微信支付！', 'error');
                }
            }
        }
        if($paytype=='alipay'){
            $pay_type='03';
        }
		$biz_content=array(
			'appId'=>$this->config['app_id'],
			'trxChannel'=>$pay_type,
            'outOrderId'=> $pay_log['tid']?:$pay_log['ordersn'],
			'outVendorId'=>$this->config['outVendorId'],
			'outUserId'=>$pay_log['mid'],
			'payAmount'=>$pay_log['fee'],
            'payType'=>'01',
            'notifyUrl'=>$pay_log['notify_url']?:SITEROOT .'addons/jy_icbcpay/notify.php',
			'jumpUrl'=>custom_url($pay_log['back_url'],true),
			'goodsName'=>$pay_log['title'],
			'trxIp'=>getip(),
			'tpAppId'=>$this->config['sub_appid'],
		);
        $payment_params = array(
            'app_id'=>$this->config['app_id'],
            'msg_id'=>$pay_log['tid']?:$pay_log['ordersn'],
			'biz_content'=>$biz_content,
			
        );
		if($pay_log['openid'] || $_SESSION['openid']){
			$payment_params['tpOpenId']=$pay_log['openid']?:$_SESSION['openid'];
		}
        $res=$this->request('https://gw.open.icbc.com.cn/ui/jft/ui/pay/h5/V3',$payment_params);
        //file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 支付记录:" . json_encode($res)."\r\n", FILE_APPEND);
		if($res['return_code']!='success'){
			//exi('支付失败，失败原因:'.$res['return_msg'],'error');
		}
        return $res;
    }
	public function request($url,$post=null,$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$sign=$this->getSign($post);
	    $post['sign']=$sign;
		$post['timestamp']=date('Y-m-d H:i:s');
		$post=ijson_encode($post);
		$rurl=$url;
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_post($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="支付错误, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $result['content'];
	}
	/**
     * 作用：格式化参数
     */
    public function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort ( $paraMap );
        foreach ( $paraMap as $k => $v ) {
            if ($urlencode) {
                $v = urlencode ( $v );
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen ( $buff ) > 0) {
            $reqPar = substr ( $buff, 0, strlen ( $buff ) - 1 );
        }
        return $reqPar;
    }
    /**
     * 作用：生成签名
     */
    public function getSign($Obj, $key='') {
		$key=$this->config['zwechat_key'];
        foreach ( $Obj as $k => $v ) {
            $Parameters [$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort ( $Parameters );
        $String = $this->formatBizQueryParaMap ($Parameters, false);
        //签名步骤二：MD5加密
        $String = md5 ( $String . $key );
        //签名步骤三：所有字符转为大写
        $result_ = strtoupper ( $String );
        return $result_;
    }
}